import {Component, OnInit, ViewChild} from '@angular/core';
import {ModalDirective} from 'ngx-bootstrap';
import {AliyunOssOutputUrl} from '../../../../../config/api';
import {LotterySpellService} from './lottery-spell-service';
import {LocalStorageService} from '../../../../lib/service/local-storage.service';
import {Router} from '@angular/router';
import * as moment from 'moment';

export class AddPennyParams {
  applet_uuid;
  name;
  start_date;
  end_date;
  number: number;
  round = '5';
  min_awards;
  price = 0.01;
  activity_goods_prize;
  new_open_group = 0; // 是否新人开团  0不是 1是
  new_offer = 0; // 是否新人参团
}

export class EditPennyParams {
  applet_uuid;
  name;
  start_date;
  end_date;
  number: number;
  round: string;
  min_awards: string;
  price;
  activity_goods_prize;
  id;
  new_open_group; // 是否新人开团  0不是 1是
  new_offer; // 是否新人参团
}


@Component({
  selector: 'app-lottery-spell',
  templateUrl: './lottery-spell.component.html',
  styleUrls: ['./lottery-spell.component.scss'],
  providers: [LotterySpellService, LocalStorageService]
})
export class LotterySpellComponent implements OnInit {

  applet_uuid;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  curDate;
  activityList = [];
  editSpell = false;
  status = '进行中';
  groupList = [];
  allGoodsNum: number;
  keyWordDlg: string;  // 添加商品..弹窗中，搜索的商品名字
  groupIdDlg = 0;  // 添加商品..弹窗中，选中的分组id
  goodsListDlg = [];
  prize = [{class: '一等奖', level: 1, goods_sku: [], type: null, coupon: {id: null}}];
  editPrize = [];
  checkedPrizeClass: number;
  activityStatus;
  operateId;
  winnerInfo = [];
  addPennyParams = new AddPennyParams();
  editPennyParams = new EditPennyParams();
  prizeType = 1;
  canSetCoupon = false;
  coupon_name;
  cardList = [];

  type: string;
  message: string;
  isShow = false;
  totalItems: number;
  itemsPerPage = 12;
  currentPage = 1;
  totalItemsDlg: number;
  itemsPerPageDlg = 4;
  currentPageDlg = 1;

  @ViewChild('addPrizeModal') public addPrizeModal: ModalDirective;
  @ViewChild('addCouponModal') public addCouponModal: ModalDirective;
  @ViewChild('changeStatusModal') public changeStatusModal: ModalDirective;
  @ViewChild('prizeWinnerModal') public prizeWinnerModal: ModalDirective;
  @ViewChild('delModal') public delModal: ModalDirective;

  constructor(private router: Router,
              private localStorageService: LocalStorageService,
              private lotterySpellService: LotterySpellService) {
  }

  ngOnInit() {
    this.getGroupList();
    this.getDlgGoodsList(1);
    this.applet_uuid = this.localStorageService.getNowApplet().applet_uuid;
    this.curDate = moment().format('YYYY-MM-DD');
    this.getPennyList();
  }

  choseType(status) {
    this.status = status;
    this.editSpell = false;
    if (status !== '新建拼团') {
      this.getPennyList();
    }
  }

  // 获取一分拼团列表
  getPennyList() {
    this.lotterySpellService.getPennyList(this.currentPage, this.itemsPerPage, this.status).subscribe(
      res => {
        this.currentPage = res.data.current_page;
        this.totalItems = res.data.total;
        this.activityList = res.data.data;
        this.activityList.every((val, idx, array) => {
          val.shopping_info.total = parseInt(val.shopping_info.ing) + parseInt(val.shopping_info.over) + parseInt(val.shopping_info.dead);
          return true;
        });
      }
    );
  }

  // 获取商品分组列表
  getGroupList() {
    this.lotterySpellService.getGroupList().subscribe(
      res => {
        this.groupList = res.data.data;
        this.lotterySpellService.getGoodsList(1, 999).subscribe(
          res1 => {
            this.allGoodsNum = res1.data.data.length;
          }
        );
        this.groupList.every((val, idx, array) => {
          this.lotterySpellService.getGoodsList(1, 999, val.id).subscribe(
            res2 => {
              val.goodsNum = res2.data.data.length;
            }
          );
          return true;
        });
      }
    );
  }

  // 添加商品..弹框中的搜索与重置
  searchDlg() {
    this.currentPageDlg = 1;
    if (this.prizeType === 1) {
      this.getDlgGoodsList(1, this.groupIdDlg, '上架', this.keyWordDlg);
    } else {
      this.getCouponList();
    }
  }

  resetDlg() {
    if (this.prizeType === 1) {
      this.keyWordDlg = '';
      this.groupIdDlg = 0;
      this.getDlgGoodsList(1, this.groupIdDlg, '上架');
    } else {
      this.coupon_name = '';
      this.getCouponList();
    }
  }

  // 获取所有的商品列表，显示在弹框中
  getDlgGoodsList(page: number, applet_goods_category_id?: number, status?: string, keyword?: string, pagesize?: number) {
    const _pageSize = pagesize || 4;
    this.lotterySpellService.getGoodsList(
      page, _pageSize,
      applet_goods_category_id,
      status,
      '',
      keyword
    ).subscribe(
      res => {
        if (res.code === 2000) {
          this.currentPageDlg = res.data.current_page;
          this.totalItemsDlg = res.data.total;
          this.goodsListDlg = res.data.data;
          const ids = [];
          this.goodsListDlg.every((val, idx, array) => {
            ids.push(val.id);
            return true;
          });
          this.lotterySpellService.getbindListAll(JSON.stringify(ids)).subscribe(
            res1 => {
              this.goodsListDlg.every((val, idx, array) => {
                val.goods_category = [];
                res1.data.every((val1, idx1, array1) => {
                  if (val.id === val1.goods_id) {
                    val.goods_category.push({name: val1.name, id: val1.applet_goods_category_id});
                  }
                  return true;
                });
                return true;
              });
            }
          );
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 获取卡券列表
  getCouponList() {
    this.lotterySpellService.getCouponList(this.currentPageDlg, this.itemsPerPageDlg, this.coupon_name).subscribe(res => {
      this.totalItemsDlg = res.data.total;
      this.cardList = res.data.data;
      if (!!res.data.data.length) {
        res.data.data.every((val, idx, array) => {
          if (val.in_stock_type === 1 && !!val.card_coupons_used_report) {
            val.remain = val.in_stock - val.card_coupons_used_report.used_total;
          } else {
            val.remain = '不限';
          }
          return true;
        });
      }
    });
  }

  pageChanged(event: any): void {
    this.currentPage = event.page;
    this.getPennyList();
  }

  dlgPageChanged(event: any): void {
    if (this.prizeType === 1) {
      this.getDlgGoodsList(event.page, this.groupIdDlg, '上架', this.keyWordDlg);
    } else {
      this.getCouponList();
    }
  }

  // 修改奖品类型
  changePrizeType(type: number) {
    this.prizeType = type;
    this.currentPageDlg = 1;
    if (this.type === 'goods') {
      this.itemsPerPageDlg = 4;
      this.getDlgGoodsList(1, this.groupIdDlg, '上架', this.keyWordDlg);
    } else {
      this.itemsPerPageDlg = 7;
      this.getCouponList();
    }
  }

  // 出现奖品弹窗
  showPrizeModal(i) {
    this.addPrizeModal.show();
    this.checkedPrizeClass = i;
    if (i === 0) {
      this.prizeType = 1;
      this.canSetCoupon = false;
    } else {
      this.canSetCoupon = true;
    }
  }

  // 选中商品选项
  checkedPrize(item, type) {
    if (!this.editSpell) {
      this.prize[this.checkedPrizeClass]['type'] = type;
      if (type === 1) {
        this.prize[this.checkedPrizeClass]['goods'] = item;
        this.addPrizeModal.hide();
        this.lotterySpellService.getGoodsSkuList(item.id).subscribe(
          res => {
            this.prize[this.checkedPrizeClass].goods_sku = res.data.data;
            if (res.data.data.length === 1) {
              this.prize[this.checkedPrizeClass].goods_sku[0].selected = true;
            } else {
              this.prize[this.checkedPrizeClass].goods_sku.every((val, idx, array) => {
                val.selected = false;
                return true;
              });
            }
          });
      } else {
        this.prize[this.checkedPrizeClass]['coupon'] = item;
        this.addPrizeModal.hide();
      }
    } else {
      this.editPrize[this.checkedPrizeClass]['type'] = type;
      if (type === 1) {
        this.editPrize[this.checkedPrizeClass]['goods'] = item;
        this.addPrizeModal.hide();
        this.lotterySpellService.getGoodsSkuList(item.id).subscribe(
          res => {
            this.editPrize[this.checkedPrizeClass].goods_sku = res.data.data;
            if (res.data.data.length === 1) {
              this.editPrize[this.checkedPrizeClass].goods_sku[0].selected = true;
            } else {
              this.editPrize[this.checkedPrizeClass].goods_sku.every((val, idx, array) => {
                val.selected = false;
                return true;
              });
            }
          });
      } else {
        this.editPrize[this.checkedPrizeClass]['coupon'] = item;
        this.addPrizeModal.hide();
      }
    }
  }

  // 选中商品sku
  checkedSku(goods_sku, ite) {
    goods_sku.every((val, idx, array) => {
      val.selected = false;
      return true;
    });
    ite.selected = true;
  }

  // 增加奖项
  addAwards() {
    if (!this.editSpell) {
      const len = this.prize.length;
      let peize_item;
      switch (len) {
        case 1:
          peize_item = {class: '二等奖', level: 2, goods_sku: []};
          break;
        case 2:
          peize_item = {class: '三等奖', level: 3, goods_sku: []};
          break;
        case 3:
          peize_item = {class: '四等奖', level: 4, goods_sku: []};
          break;
        case 4:
          peize_item = {class: '五等奖', level: 5, goods_sku: []};
          break;
        case 5:
          return;
      }
      this.prize.push(peize_item);
    } else {
      const len = this.editPrize.length;
      let peize_item;
      switch (len) {
        case 1:
          peize_item = {class: '二等奖', level: 2, goods_sku: []};
          break;
        case 2:
          peize_item = {class: '三等奖', level: 3, goods_sku: []};
          break;
        case 3:
          peize_item = {class: '四等奖', level: 4, goods_sku: []};
          break;
        case 4:
          peize_item = {class: '五等奖', level: 5, goods_sku: []};
          break;
        case 5:
          return;
      }
      this.editPrize.push(peize_item);
    };
  }

  // 新增一分拼团
  addPenny() {
    this.addPennyParams.applet_uuid = this.applet_uuid;
    this.addPennyParams.activity_goods_prize = [];
    let canAdd = true;
    this.prize.every((val, idx, array) => {
      const data = {};
      data['level'] = val.level;
      data['type'] = val.type;
      data['number'] = val['number'];
      if (val.type === 1) {
        if (!val.goods_sku.length) {
          this.type = 'info';
          this.message = '请选择奖品内容';
          this.isShow = true;
          canAdd = false;
          return false;
        }
        val.goods_sku.every((val1, idx1, array1) => {
          if (!!val1.selected) {
            data['id'] = val1.id;
            return false;
          } else {
            return true;
          }
        });
        if (!data['id']) {
          this.type = 'info';
          this.message = '请选择商品规格';
          this.isShow = true;
          canAdd = false;
          return false;
        }
      } else {
        data['id'] = val.coupon.id;
      }
      this.addPennyParams.activity_goods_prize.push(data);
      return true;
    });
    if (!canAdd) {
      return;
    }
    this.addPennyParams.activity_goods_prize = JSON.stringify(this.addPennyParams.activity_goods_prize);
    this.lotterySpellService.judge(this.applet_uuid).subscribe(res1 => {
      if (!!res1.data.status) {
        this.lotterySpellService.addPenny(this.addPennyParams).subscribe(
          res => {
            if (res.code === 2000) {
              this.isShow = true;
              this.type = 'success';
              this.message = '添加成功';
              if (this.addPennyParams.start_date > this.curDate) {
                this.status = '未开始';
              } else {
                this.status = '进行中';
              }
              this.getPennyList();
            } else {
              this.type = 'error';
              this.isShow = true;
              this.message = res.message;
            }
          }
        );
      } else {
        this.type = 'error';
        this.isShow = true;
        this.message = '新建抽奖团前，请先添加抽奖模板';
      }
    });
  }

  editSpellPage(item) {
    this.editPennyParams.applet_uuid = this.applet_uuid;
    this.editPennyParams.id = item.id.toString();
    this.editPennyParams.name = item.name;
    this.editPennyParams.start_date = item.start_date;
    this.editPennyParams.end_date = item.end_date;
    this.editPennyParams.number = item.activity_goods[0].number;
    this.editPennyParams.round = item.activity_goods[0].round;
    this.editPennyParams.min_awards = item.activity_goods[0].min_awards;
    this.editPennyParams.new_open_group = item.activity_goods[0].new_open_group;
    this.editPennyParams.new_offer = item.activity_goods[0].new_offer;
    this.editPennyParams.price = item.activity_goods[0].activity_goods_sku[0].price / 1000;
    this.editPrize = [];
    this.editSpell = true;
    this.lotterySpellService.getPennyInfo(item.id).subscribe(
      res => {
        res.data.activity_goods[0].activity_goods_prize.every((val, idx, array) => {
          const prize_info = JSON.parse(val.prize_info);
          let data;
          if (idx === 0) {
            data = {class: '一等奖', level: 1, goods_sku: []};
          } else if (idx === 1) {
            data = {class: '二等奖', level: 2, goods_sku: []};
          } else if (idx === 2) {
            data = {class: '三等奖', level: 3, goods_sku: []};
          } else if (idx === 3) {
            data = {class: '四等奖', level: 4, goods_sku: []};
          } else {
            data = {class: '五等奖', level: 5, goods_sku: []};
          }
          data['type'] = val.type;
          data['number'] = val.number;
          if (val.type === 1) {
            data['goods'] = val.goods;
            this.lotterySpellService.getGoodsSkuList(prize_info.goods_id).subscribe(
              rs => {
                data.goods_sku = rs.data.data;
                data.goods_sku.every((val1, idx1, array1) => {
                  if (val1.id === prize_info.id) {
                    val1.selected = true;
                  } else {
                    val1.selected = false;
                  }
                  return true;
                });
              });
          } else {
            data['coupon'] = JSON.parse(val.prize_info);
          }
          this.editPrize.push(data);
          return true;
        });
      }
    );
  }

  editPenny() {
    this.editPennyParams.activity_goods_prize = [];
    this.editPrize.every((val, idx, array) => {
      const data = {};
      data['level'] = val.level;
      data['type'] = val.type;
      data['number'] = val['number'];
      if (val.type === 1) {
        val.goods_sku.every((val1, idx1, array1) => {
          if (!!val1.selected) {
            data['id'] = val1.id;
            return false;
          } else {
            return true;
          }
        });
      } else {
        data['id'] = val.coupon.id;
      }
      this.editPennyParams.activity_goods_prize.push(data);
      return true;
    });
    this.editPennyParams.activity_goods_prize = JSON.stringify(this.editPennyParams.activity_goods_prize);
    this.lotterySpellService.editPenny(this.editPennyParams).subscribe(
      res => {
        if (res.code === 2000) {
          this.isShow = true;
          this.type = 'success';
          this.message = '添加成功';
          this.editSpell = false;
          if (this.editPennyParams.start_date > this.curDate) {
            this.status = '未开始';
          } else {
            this.status = '进行中';
          }
          this.getPennyList();
        } else {
          this.isShow = true;
          this.type = 'error';
          this.message = res.message;
        }
      }
    );
  }

  // 删除拼团
  delSpell(id) {
    this.operateId = id;
    this.delModal.show();
  }

  submitDelActivity() {
    this.lotterySpellService.delActivity(this.operateId).subscribe(
      res => {
        if (res.code === 2000) {
          this.delModal.hide();
          this.type = 'success';
          this.message = '';
          this.isShow = true;
          this.getPennyList();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 修改活动状态
  changeStatus(id, status) {
    this.activityStatus = status;
    this.operateId = id;
    this.changeStatusModal.show();
  }

  confirmChangeStatus() {
    this.lotterySpellService.changePennyStatus(this.operateId, this.activityStatus).subscribe(
      res => {
        if (res.code === 2000) {
          this.changeStatusModal.hide();
          this.isShow = true;
          this.type = 'success';
          this.message = '状态修改成功';
          this.getPennyList();
        } else {
          this.isShow = true;
          this.type = 'error';
          this.message = res.message;
        }
      }
    );
  }

  // 重新开团
  createSpellAgain(item) {
    this.addPennyParams.applet_uuid = this.applet_uuid;
    this.addPennyParams.name = item.name;
    this.addPennyParams.number = item.activity_goods[0].number;
    this.addPennyParams.round = item.activity_goods[0].round;
    this.addPennyParams.min_awards = item.activity_goods[0].min_awards;
    this.addPennyParams.new_open_group = item.activity_goods[0].new_open_group;
    this.addPennyParams.new_offer = item.activity_goods[0].new_offer;
    this.addPennyParams.price = item.activity_goods[0].activity_goods_sku[0].price / 1000;
    this.prize = [];
    this.lotterySpellService.getPennyInfo(item.id).subscribe(
      res => {
        res.data.activity_goods[0].activity_goods_prize.every((val, idx, array) => {
          const prize_info = JSON.parse(val.prize_info);
          let data;
          if (idx === 0) {
            data = {class: '一等奖', level: 1, goods_sku: []};
          } else if (idx === 1) {
            data = {class: '二等奖', level: 2, goods_sku: []};
          } else {
            data = {class: '三等奖', level: 3, goods_sku: []};
          }
          data['goods'] = val.goods;
          data['number'] = val.number;
          this.lotterySpellService.getGoodsSkuList(prize_info.goods_id).subscribe(
            rs => {
              data.goods_sku = rs.data.data;
              data.goods_sku.every((val1, idx1, array1) => {
                if (val1.id === prize_info.id) {
                  val1.selected = true;
                } else {
                  val1.selected = false;
                }
                return true;
              });
            });
          this.prize.push(data);
          return true;
        });
        this.status = '新建拼团';
      }
    );
  }

  // 获取中奖详情
  getPrizeWinner(id) {
    this.lotterySpellService.getPrizeWinner(id).subscribe(
      res => {
        if (res.code === 2000) {
          this.winnerInfo = [];
          res.data.every((val, idx, array) => {
            const len = this.winnerInfo.length,
             level = val.activity_goods_level,
              name = val.applet_member.nickName || '';
            let nickName;
            if (name.length > 3) {
              nickName = name.substring(0, 3) + '**' + name.substring(name.length - 3, name.length);
            } else {
              nickName = name;
            }
            const data = {img: val.applet_member.avatarUrl, name: nickName, order_no: val.order_no};
            if (len < level) {
              const info = [data];
              this.winnerInfo.push({info: info});
            } else {
              this.winnerInfo[level - 1].info.push(data);
            }
            return true;
          });
          this.prizeWinnerModal.show();
        } else {
          this.isShow = true;
          this.type = 'error';
          this.message = res.message;
        }
      }
    );
  }

  checkedNew(container) {
    if (this.addPennyParams[container] === 0) {
      this.addPennyParams[container] = 1;
    } else {
      this.addPennyParams[container] = 0;
    }
  }
}
